from fastapi import APIRouter, Depends, Request 
from typing import Annotated
from sqlalchemy.ext.asyncio import AsyncSession
from app.services.user import UserScoreService
from app.core.db.database import async_get_db
from app.util.jwt_helper import validate_auth_header


router_score = APIRouter(tags=["积分服务"], prefix="/score")


@router_score.get("/current", description="获取当前用户积分")
async def get_user_score(request: Request, db: Annotated[AsyncSession, Depends(async_get_db)]):
    user_payload_id = validate_auth_header(request)
    user_score_service = UserScoreService(db)
    user_score = await user_score_service.get_user_score(user_payload_id)
    return {
        "success": True,
        "message": "获取用户积分成功",
        "data": {
            'payload_id': user_score.get("payload_id"),
            'score': user_score.get("total_score") - user_score.get("used_score"),
        }
    }

@router_score.post("/sign", description="用户每日签到")
async def user_sign(request: Request, db: Annotated[AsyncSession, Depends(async_get_db)]):
    redis_client = request.app.state.redis

    user_payload_id = validate_auth_header(request)
    user_score_service = UserScoreService(db)
    
    # 检查用户今日是否已签到
    from datetime import datetime
    
    # 构建Redis键，格式为 user:sign:{user_id}:{date}
    today = datetime.now().strftime('%Y%m%d')
    sign_key = f"user:sign:{user_payload_id}:{today}"
    
    # 检查Redis中是否存在今日签到记录
    if await redis_client.exists(sign_key):
        return {
            "success": False,
            "message": "今日已签到",
            "data": None
        }
    
    # 设置签到记录，并设置过期时间为24小时
    await redis_client.setex(sign_key, 86400, 1)
    
    # 执行签到并增加积分
    sign_score = await user_score_service.add_sign_score(user_payload_id)
    
    return {
        "success": True,
        "message": "签到成功",
        "data": {
            "added_score": sign_score
        }
    }

@router_score.get("/sign/check", description="检查用户今日是否已签到")
async def check_user_sign(request: Request):
    redis_client = request.app.state.redis
    
    user_payload_id = validate_auth_header(request)
    from datetime import datetime
    
    # 构建Redis键，格式为 user:sign:{user_id}:{date}
    today = datetime.now().strftime('%Y%m%d')
    sign_key = f"user:sign:{user_payload_id}:{today}"
    
    # 检查Redis中是否存在今日签到记录
    is_signed = await redis_client.exists(sign_key)
    
    return {
        "success": True,
        "message": "查询签到状态成功",
        "data": {
            "is_signed": bool(is_signed)
        }
    }
